package com.huanke.iot.gateway.io.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huanke.iot.base.dao.device.DeviceMapper;
import com.huanke.iot.base.dao.device.data.DeviceOperLogMapper;
import com.huanke.iot.gateway.io.AbstractHandler;
import com.huanke.iot.gateway.mqttlistener.MqttService;
import com.huanke.iot.gateway.onlinecheck.OnlineCheckService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class LastWillHandler  extends AbstractHandler {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DeviceOperLogMapper deviceOperLogMapper;

    @Autowired
    private MqttService mqttService;

    @Autowired
    private OnlineCheckService onlineCheckService;

    @Value("${useNewGateway}")
    private String useNewGateway;


    @Override
    protected String getTopicType() {
        return "lastwill";
    }

    @Override
    public void doHandler(String topic, byte[] payloads) {
        Integer deviceId = getDeviceIdFromTopic(topic);
        log.info("lastWillDeviceId = {}",deviceId);
        JSONObject jsonObject = JSON.parseObject(new String(payloads));
        if(!Boolean.FALSE.equals(Boolean.valueOf(useNewGateway))){
            return;
        }

        Integer online = jsonObject.getInteger("online");
        //DevicePo updatePo = new DevicePo();
        //updatePo.setId(deviceId);

        //将离线记录写入日志
        //DeviceOperLogPo deviceOperLogPo= new DeviceOperLogPo();
        //deviceOperLogPo.setDeviceId(deviceId);
        //deviceOperLogPo.setFuncId("410");

        //deviceOperLogPo.setCreateTime(System.currentTimeMillis());
        if(new Integer(0).equals(online)){
            //更新主设备状态
            //updatePo.setOnlineStatus(DeviceConstant.ONLINE_STATUS_NO);
            //deviceOperLogPo.setFuncValue("0");
            //重设设备在线状态
            onlineCheckService.resetOffline(deviceId);
        }else if(new Integer(1).equals(online)){
            //设备再次上线，主动询问数据
            //String message = "{'datas': [{'childid': '0','type': ''}],'msg_id': 'feafb66e8','msg_type': 'get'}";
            String message = "{\"datas\": [{\"childid\": \"0\",\"type\": \"\"}],\"msg_id\": \"feafb66e8\",\"msg_type\": \"get\"}";
            mqttService.sendMessage("/down2/control/"+deviceId,message,false);
            //重设设备在线状态
            onlineCheckService.resetOnline(deviceId);

            //updatePo.setOnlineStatus(DeviceConstant.ONLINE_STATUS_YES);
            //deviceOperLogPo.setFuncValue("1");
        }
        //deviceMapper.updateById(updatePo);
        //this.deviceOperLogMapper.insert(deviceOperLogPo);
    }
}
